import React, { useState, useEffect, useCallback, useRef } from 'react'
import { Folder, Plus, Settings } from 'lucide-react'
import { FileInfo } from './types/electron'
import ResponsiveEditor from './editor/ResponsiveEditor'
import GitSidebar from './components/GitSidebar'
import AIContextMenu from './components/AIContextMenu'
import SettingsPanel from './components/SettingsPanel'
import { createNotificationManager } from './components/Notification'

interface AppState {
  currentFile: {
    path: string | null
    content: string
  } | null
  files: FileInfo[]
  aiMenu: {
    visible: boolean
    position: { x: number; y: number }
    selectedText: string
  }
  settingsPanel: {
    visible: boolean
  }
  theme: 'light' | 'dark' | 'auto'
  sidebarCollapsed: boolean
}

const App: React.FC = () => {
  const [state, setState] = useState<AppState>({
    currentFile: null,
    sidebarCollapsed: false,
    files: [],
    aiMenu: {
      visible: false,
      position: { x: 0, y: 0 },
      selectedText: ''
    },
    settingsPanel: {
      visible: false
    },
    theme: 'auto'
  })
  const notificationManager = useRef(createNotificationManager()).current

  useEffect(() => {
    // Initialize the app
    const initializeApp = async () => {
      try {
        // Check if we're in Electron environment
        if (window.electronAPI) {
          // Load recent files or open default directory
          const recentFiles = await window.electronAPI.getRecentFiles()
          setState(prev => ({ ...prev, files: recentFiles }))
        } else {
          // Fallback for browser environment
          console.log('Running in browser environment, using mock data')
          setState(prev => ({ 
            ...prev, 
            files: [
              { path: 'example.md', openedTime: Date.now(), modifiedTime: Date.now() },
              { path: 'test.md', openedTime: Date.now(), modifiedTime: Date.now() }
            ] 
          }))
        }
      } catch (error) {
        console.error('Failed to initialize app:', error)
        // Fallback for browser environment
        setState(prev => ({ 
          ...prev, 
          files: [
            { path: 'example.md', openedTime: Date.now(), modifiedTime: Date.now() },
            { path: 'test.md', openedTime: Date.now(), modifiedTime: Date.now() }
          ] 
        }))
      }
    }

    initializeApp()
  }, [])

  // Handle IPC events from main process
  useEffect(() => {
    const handleFileNewIPC = () => {
      setState(prev => ({
        ...prev,
        currentFile: {
          path: '',
          content: ''
        }
      }))
    }

    const handleFileOpenDialogIPC = async () => {
      try {
        if (window.electronAPI) {
          const fileData = await window.electronAPI.openFile()
          if (fileData) {
            setState(prev => ({
              ...prev,
              currentFile: {
                path: fileData.path,
                content: fileData.content
              }
            }))
          }
        }
      } catch (error) {
        console.error('Failed to open file dialog:', error)
      }
    }

    const handleFileSaveIPC = () => {
      if (state.currentFile) {
        handleFileSave(state.currentFile.content)
      }
    }

    const handleFileSaveAsIPC = () => {
        if (state.currentFile && window.electronAPI) {
          window.electronAPI.saveFileAs(state.currentFile.content).catch(error => {
            console.error('Failed to save file as:', error)
          })
        }
      }

    // Register IPC event listeners using electronAPI
    const unsubscribeNewFile = window.electronAPI?.onFileChanged?.(() => {})
    // Note: We would need to implement these in preload.ts if they don't exist
    // For now, using window events as fallback

    const handleNewFile = (event: any) => handleFileNewIPC()
    const handleOpenDialog = (event: any) => handleFileOpenDialogIPC()
    const handleSave = (event: any) => handleFileSaveIPC()
    const handleSaveAs = (event: any) => handleFileSaveAsIPC()

    window.addEventListener('file:new', handleNewFile)
    window.addEventListener('file:open-dialog', handleOpenDialog)
    window.addEventListener('file:save', handleSave)
    window.addEventListener('file:save-as', handleSaveAs)

    return () => {
      window.removeEventListener('file:new', handleNewFile)
      window.removeEventListener('file:open-dialog', handleOpenDialog)
      window.removeEventListener('file:save', handleSave)
      window.removeEventListener('file:save-as', handleSaveAs)
      unsubscribeNewFile?.()
    }
  }, [state.currentFile])

  const handleFileOpen = async (filePath: string) => {
    try {
      if (window.electronAPI) {
        const fileData = await window.electronAPI.openFile(filePath)
        if (fileData) {
          setState(prev => ({
            ...prev,
            currentFile: {
              path: fileData.path,
              content: fileData.content
            }
          }))
          
          // 优化：只在必要时刷新文件列表
          // 检查当前文件是否已在文件列表中，如果不在则刷新
          const fileExists = state.files.some(file => file.path === fileData.path)
          if (!fileExists) {
            const recentFiles = await window.electronAPI.getRecentFiles()
            setState(prev => ({ ...prev, files: recentFiles }))
          } else {
            // 如果文件已存在，只更新当前打开的文件，不刷新整个列表
            setState(prev => ({ ...prev, currentFile: { path: fileData.path, content: fileData.content } }))
          }
        }
      } else {
        // Fallback for browser environment
        console.log('Opening file in browser environment:', filePath)
        setState(prev => ({
          ...prev,
          currentFile: {
            path: filePath,
            content: `# ${filePath}\n\nThis is a mock file content for browser environment.`
          }
        }))
      }
    } catch (error) {
      console.error('Failed to open file:', error)
    }
  }

  const handleFileSave = async (content: string) => {
    if (!state.currentFile) return

    try {
      if (window.electronAPI) {
        const savedPath = await window.electronAPI.saveFile(
          content,
          state.currentFile?.path || undefined
        )
        setState(prev => ({
          ...prev,
          currentFile: prev.currentFile
            ? { ...prev.currentFile, path: savedPath }
            : null
        }))
        
        // 优化：只在必要时刷新文件列表
        // 如果文件路径发生变化（新保存的文件），则刷新文件列表
        if (savedPath !== state.currentFile?.path) {
          const recentFiles = await window.electronAPI.getRecentFiles()
          setState(prev => ({ ...prev, files: recentFiles }))
        }
      } else {
        // Fallback for browser environment
        console.log('Saving file in browser environment:', state.currentFile?.path || 'Untitled')
        // In browser, we can't actually save files, but we can simulate it
        console.log('File content:', content)
      }
    } catch (error) {
      console.error('Failed to save file:', error)
    }
  }

  const handleNewFileWithName = async () => {
    try {
      // 使用 Electron 的输入对话框
      const result = await window.electronAPI.showInputDialog({
        title: '请输入新文件名（包含扩展名，如：document.md）',
        default: 'untitled.md'
      })

      if (!result.canceled && result.value) {
        const fileName = result.value
        setState(prev => ({
          ...prev,
          currentFile: {
            path: fileName,
            content: `# ${fileName.replace(/\.[^/.]+$/, '')}\n\nStart writing here...`
          }
        }))
      }
    } catch (error) {
      console.error('Failed to show input dialog:', error)
    }
  }

  const handleAIAction = async (action: string, text: string) => {
    try {
      const result = await window.electronAPI.invokeAI(action, text)
      // The editor will handle the text replacement
      return result
    } catch (error) {
      console.error('AI action failed:', error)
      throw error
    }
  }

  const handleAIStreamChunk = (chunk: string) => {
    // Update the editor with streaming content
    // This will be called from the editor component
    console.log('AI stream chunk:', chunk)
  }

  const handleAIStreamComplete = (result: string) => {
    // Final replacement with complete result
    // This will be called from the editor component
    console.log('AI stream complete:', result)
    
    // Show success notification
    notificationManager.show({
      type: 'success',
      title: 'AI 操作完成',
      message: '文本处理成功完成',
      duration: 3000
    })
  }

  const handleAIStreamError = (error: string) => {
    console.error('AI streaming error:', error)
    notificationManager.show({
      type: 'error',
      title: 'AI 操作失败',
      message: error,
      duration: 5000
    })
  }

  const showAIMenu = (position: { x: number; y: number }, selectedText: string) => {
    setState(prev => ({
      ...prev,
      aiMenu: {
        visible: true,
        position,
        selectedText
      }
    }))
  }

  const hideAIMenu = () => {
    setState(prev => ({
      ...prev,
      aiMenu: {
        ...prev.aiMenu,
        visible: false
      }
    }))
  }

  const showSettingsPanel = () => {
    setState(prev => ({
      ...prev,
      settingsPanel: { visible: true }
    }))
  }

  const hideSettingsPanel = () => {
    setState(prev => ({
      ...prev,
      settingsPanel: { visible: false }
    }))
  }

  const toggleSidebar = () => {
    setState(prev => ({
      ...prev,
      sidebarCollapsed: !prev.sidebarCollapsed
    }))
  }

  
  return (
    <div className="fixed inset-0 bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 overflow-hidden">
      {/* Add padding-top to account for window controls */}
      <div className="flex pt-8 h-full overflow-hidden">
        {/* Sidebar */}
        <GitSidebar
          files={state.files}
          currentFile={state.currentFile?.path || null}
          onFileSelect={handleFileOpen}
          onNewFile={handleNewFileWithName}
          onSaveFile={() => {
            if (state.currentFile) {
              handleFileSave(state.currentFile.content)
            }
          }}
          onOpenFile={async () => {
            // Open file dialog and handle selected file
            try {
              if (window.electronAPI) {
                const fileData = await window.electronAPI.openFile()
                if (fileData) {
                  setState(prev => ({
                    ...prev,
                    currentFile: {
                      path: fileData.path,
                      content: fileData.content
                    }
                  }))
                }
              } else {
                // Fallback for browser environment
                console.log('Opening file dialog in browser environment')
                // In browser, we can't open a file dialog, so we'll create a new file
                setState(prev => ({
                  ...prev,
                  currentFile: {
                    path: 'untitled.md',
                    content: '# Untitled Document\n\nStart writing here...'
                  }
                }))
              }
            } catch (error) {
              console.error('Failed to open file:', error)
            }
          }}
          onSettings={showSettingsPanel}
          isCollapsed={state.sidebarCollapsed}
          onToggleCollapse={toggleSidebar}
        />

        {/* Main Editor Area */}
        <div className="flex-auto flex flex-col min-w-0">
          {state.currentFile ? (
            <ResponsiveEditor
              content={state.currentFile.content}
              filePath={state.currentFile.path || 'untitled.md'}
              onSave={handleFileSave}
              onAIAction={handleAIAction}
              onShowAIMenu={showAIMenu}
              sidebarWidth={state.sidebarCollapsed ? 64 : 256}
            />
          ) : (
            <div className="flex-1 flex items-center justify-center min-h-0">
              <div className="text-center max-w-md mx-auto p-8">
                <div className="mb-8">
                  <div className="w-20 h-20 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
                    <span className="text-3xl">📝</span>
                  </div>
                  <h1 className="text-4xl font-bold text-gray-900 dark:text-gray-100 mb-3">
                    IntelliMark
                  </h1>
                  <p className="text-lg text-gray-600 dark:text-gray-400 font-medium">
                    AI-Powered Markdown Editor
                  </p>
                  <p className="text-sm text-gray-500 dark:text-gray-500 mt-2">
                    Write smarter with AI assistance
                  </p>
                </div>

                <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-200/60 dark:border-gray-700/60">
                  <h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-4">快速开始</h3>
                  <div className="space-y-3 text-sm">
                    <div className="flex items-center justify-center space-x-3 text-gray-600 dark:text-gray-400">
                      <div className="w-8 h-8 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center">
                        <Folder className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                      </div>
                      <span>点击侧边栏的"Open"按钮</span>
                    </div>
                    <div className="flex items-center justify-center space-x-3 text-gray-600 dark:text-gray-400">
                      <div className="w-8 h-8 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center">
                        <Plus className="w-4 h-4 text-green-600 dark:text-green-400" />
                      </div>
                      <span>或创建新文档</span>
                    </div>
                    <div className="flex items-center justify-center space-x-3 text-gray-600 dark:text-gray-400">
                      <div className="w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
                        <span className="text-xs font-bold text-purple-600 dark:text-purple-400">⌘O</span>
                      </div>
                      <span>快捷键 Ctrl+O 打开文件</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* AI Context Menu */}
      {state.aiMenu.visible && (
        <AIContextMenu
          position={state.aiMenu.position}
          selectedText={state.aiMenu.selectedText}
          onAction={handleAIAction}
          onClose={hideAIMenu}
          onStreamChunk={handleAIStreamChunk}
          onStreamComplete={handleAIStreamComplete}
          onStreamError={handleAIStreamError}
        />
      )}

      {/* Settings Panel */}
      <SettingsPanel
        isOpen={state.settingsPanel.visible}
        onClose={hideSettingsPanel}
      />
    </div>
  )
}

export default App